<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Diary</title>
</head>
<body>
    <h1>My Diary</h1>
    <form id="diary-form">
        <label for="date">Date:</label>
        <input type="date" id="date" name="date" required><br><br>

        <label for="weather">Weather:</label>
        <input type="text" id="weather" name="weather" required><br><br>

        <label for="mood">Mood:</label>
        <input type="text" id="mood" name="mood" required><br><br>

        <label for="event">Event:</label>
        <textarea id="event" name="event" rows="4" required></textarea><br><br>

        <button type="submit">Submit</button>
    </form>

    <h2>History</h2>
    <ul id="history-list"></ul>

    <script>
        document.getElementById('diary-form').addEventListener('submit', function(event) {
            event.preventDefault();
            const formData = new FormData(event.target);
            const data = {};
            formData.forEach((value, key) => {
                data[key] = value;
            });

            fetch('/submit', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.json())
            .then(data => {
                alert(data.message);
                loadHistory();
            })
            .catch(error => console.error('Error:', error));
        });

        function loadHistory() {
            fetch('/history')
            .then(response => response.json())
            .then(entries => {
                const historyList = document.getElementById('history-list');
                historyList.innerHTML = '';
                entries.forEach(entry => {
                    const listItem = document.createElement('li');
                    listItem.textContent = `Date: ${entry.date}, Weather: ${entry.weather}, Mood: ${entry.mood}, Event: ${entry.event}`;
                    historyList.appendChild(listItem);
                });
            })
            .catch(error => console.error('Error loading history:', error));
        }

        // Load history when the page loads
        window.onload = loadHistory;
    </script>
</body>
</html>